package at.fhj.itm11.forum.service.impl;

import java.rmi.RemoteException;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.inject.Named;
import javax.xml.rpc.ServiceException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import at.fhj.itm11.forum.data.UserDAO;
import at.fhj.itm11.forum.exceptions.LoginException;
import at.fhj.itm11.forum.model.User;
import at.fhj.itm11.forum.service.UserService;
import at.fhj.itm11.forum.service.converter.DTOConverter;
import at.fhj.itm11.forum.service.converter.UserDTOConverter;
import at.fhj.itm11.forum.service.dtos.UserDTO;
import at.fhj.itm11.forum.ws.FHJForumAuthWS_PortType;
import at.fhj.itm11.forum.ws.FHJForumAuthWS_Service;

@Named
@Stateless
public class UserServiceImpl implements UserService {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Inject
	@Named("userDAOImpl")
	private UserDAO dao;

	private FHJForumAuthWS_PortType webService;
	private FHJForumAuthWS_Service serviceLocator;

	private DTOConverter<UserDTO, User> userDtoConverter = new UserDTOConverter();

	public UserDTO findById(Long id) {
		return userDtoConverter.convertToDto(dao.findById(id));
	}

	public UserDTO findByUsername(String username) {
		return userDtoConverter.convertToDto(dao.findByUsername(username));
	}

	public UserDTO login(String username, String password) {
		User user = null;

		try {
			if(webService == null) {
				setWebService(getServiceLocator().getFHJForumAuthWSPort());
			}
			
			boolean isUserOk = getWebService().authUser(username, password);

			if (isUserOk) {
				user = dao.findByUsername(username);
			}
		} catch (RemoteException e) {
			throw new LoginException(e);
		} catch (ServiceException e) {
			throw new LoginException(e);
		}

		return userDtoConverter.convertToDto(user);
	}

	public void setDao(UserDAO dao) {
		this.dao = dao;
	}

	public FHJForumAuthWS_PortType getWebService() {
		return webService;
	}

	public void setWebService(FHJForumAuthWS_PortType webService) {
		this.webService = webService;
	}

	public FHJForumAuthWS_Service getServiceLocator() {
		return serviceLocator;
	}

	public void setServiceLocator(FHJForumAuthWS_Service serviceLocator) {
		this.serviceLocator = serviceLocator;
	}

}
